package com.wechat.controller;

import com.wechat.apidoc.WxAnswerInterface;
import com.wechat.entity.Answer;
import com.wechat.entity.Question;
import com.wechat.entity.User;
import com.wechat.entity.extend.AnswerExt;
import com.wechat.entity.extend.QuestionDetailExt;
import com.wechat.service.AnswerService;
import com.wechat.service.QuestionService;
import com.wechat.service.UserService;
import com.wechat.utils.ActionResult;
import com.wechat.utils.EncryptService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;


/**
 * 微信小程序支付接口
 *
 * @author cgc
 * @date 2018/4/11
 */
@RestController
@RequestMapping("/api/v1")
public class WxAnswerController implements WxAnswerInterface {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AnswerService answerService;

    @Autowired
    private UserService userService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private EncryptService encryptService;



    /**
     * 回答问题首页获取要回答的问题
     * @param key 用户秘钥
     * @param questionId 题目ID
     * @return
     */
    @Override
    @RequestMapping(value = "/answer/index", method = RequestMethod.POST)
    public ActionResult index(String key ,Integer questionId) {

        logger.info("[获取答题首页详情接口]:{}", "key="+ key + ",questionId=" + questionId);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (questionId == null || questionId <= 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Question question = questionService.findQuestion(questionId);
            User qUser = userService.findById(question.getUserId());
            if(qUser.getId().equals(user.getId())){
                result.put("flag",1);
                result.setSuccess(true);
                result.setMessage("不能回答自己的题目");
                return result;
            }

            Answer answer = answerService.findByUserQuestionId(user.getId(),question.getId(),1);
            if(answer != null){
                result.put("flag",2);
                result.put("answerId",answer.getId());
                result.setSuccess(true);
                result.setMessage("你已经回答过此题目了");
                return result;
            }

            User questionUser = new User();
            questionUser.setNickname(qUser.getNickname());
            questionUser.setAvatarUrl(qUser.getAvatarUrl());

            result.setData(question);
            result.put("questionUser",questionUser);
            result.put("flag",0);
            result.setSuccess(true);
            result.setMessage("获取答题首页详情成功");


        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("获取答题记录详情失败");

            logger.warn("[获取答题首页详情接口异常]：", e);
        }

        return result;
    }

    /**
     * 获取题目秘钥
     * @param key
     * @param questionId
     * @return
     */
    @Override
    @RequestMapping(value = "/answer/getQuestionCode", method = RequestMethod.POST)
    public ActionResult getQuestionCode(String key, Integer questionId) {
        logger.info("[获取题目秘钥接口]:{}", "key="+ key + ",questionId=" + questionId);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (questionId == null || questionId <= 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Question question = questionService.findQuestion(questionId);
            if(!question.getUserId().equals(user.getId())){
                result.setSuccess(false);
                result.setMessage("只能加密自己的题目");
                return result;
            }

            result.setData(encryptService.encrypt(questionId.toString()));
            result.setSuccess(true);
            result.setMessage("获取题目秘钥成功");

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("获取题目秘钥失败");

            logger.warn("[获取题目秘钥接口异常]：", e);
        }

        return result;
    }

    /**
     * 回答问题首页开始答题
     * @param key 用户秘钥
     * @param questionId 题目Id
     * @return
     */
    @Override
    @RequestMapping(value = "/answer/start", method = RequestMethod.POST)
    public ActionResult start(String key ,Integer questionId) {

        logger.info("[回答问题首页开始答题接口]:{}", "key="+ key + ",questionId=" + questionId);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (questionId == null || questionId <= 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Question question = questionService.findQuestion(questionId);
            User qUser = userService.findById(question.getUserId());
            if(qUser.getId().equals(user.getId())){
                result.put("flag",false);
                result.setSuccess(true);
                result.setMessage("不能回答自己的题目");
                return result;
            }
            if(!question.getAmountStatus().equals(Question.AMOUNT_STATUS_NOT_TAKE)){
                result.put("flag",false);
                result.setSuccess(true);
                result.setMessage("红包已领完或已退回");
                return result;
            }

            Answer answer = new Answer();
            answer.setUserId(user.getId());
            answer.setQuestionId(question.getId());
            answer.setTotalNumber(question.getTotalQuestionNumber());
            answerService.save(answer);

            result.setData(answer.getId());
            result.put("flag",true);
            result.setSuccess(true);
            result.setMessage("回答问题首页开始答题成功");

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("回答问题首页开始答题失败");

            logger.warn("[回答问题首页开始答题接口异常]：", e);
        }

        return result;
    }

    /**
     * 答题界面获取题目信息
     */
    @Override
    @RequestMapping(value = "/answer/answer" ,method = RequestMethod.POST)
    public ActionResult answer(String key, Integer answerId) {
        logger.info("[获取答题界面题目信息接口]:{}", "key="+ key + ",answerId=" + answerId);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (answerId == null || answerId == 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Answer answer = answerService.findById(answerId);

            if(answer.getUserId().equals(user.getId())){

                List<QuestionDetailExt> list = questionService.questionDetailExtList(answer.getQuestionId());
                result.setData(list);
                result.setSuccess(true);
                result.setMessage("获取答题界面题目信息成功");
            }else {
                result.setSuccess(false);
                result.setMessage("无权查看该记录");
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("获取答题界面题目信息失败");

            logger.warn("[获取答题界面题目信息接口异常]：", e);
        }

        return result;
    }

    /**
     * 获取该答题对应问题下的所有答题记录
     * @param key
     * @param answerId
     * @return
     */
    @Override
    @RequestMapping(value = "/answer/getOtherAnswers" ,method = RequestMethod.POST)
    public ActionResult getOtherAnswers(String key, Integer answerId) {

        logger.info("[获取该答题对应问题下的所有答题记录接口]:{}", "key="+ key + ",answerId=" + answerId);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (answerId == null || answerId == 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Answer answer = answerService.findById(answerId);

            List<AnswerExt> list = answerService.findAnswerExtList(null,answer.getQuestionId());

            result.setData(list);
            result.setSuccess(true);
            result.setMessage("获取该答题对应问题下的所有答题记录成功");
            return result;

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("获取该答题对应问题下的所有答题记录失败");

            logger.warn("[获取该答题对应问题下的所有答题记录接口异常]：", e);
        }

        return result;
    }

    /**
     * 答案提交接口
     */
    @Override
    @RequestMapping(value = "/answer/submit" ,method = RequestMethod.POST)
    public ActionResult submit(String key, Integer answerId, String answers) {
        logger.info("[答案提交接口]:{}", "key="+ key + ",answerId=" + answerId + ",answers=" + answers);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (answerId == null || answerId == 0 || StringUtils.isBlank(answers)) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Answer answer = answerService.findById(answerId);

            if(answer.getDataState() == 1){
                result.setSuccess(true);
                result.setMessage("答案提交接口成功");
                return result;
            }

            if(answer.getUserId().equals(user.getId())){

                answerService.submitAnswers(answer,answers);

                result.setSuccess(true);
                result.setMessage("答案提交接口成功");
            }else {
                result.setSuccess(false);
                result.setMessage("无权提交");
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("答案提交失败");

            logger.warn("[答案提交接口异常]：", e);
        }

        return result;
    }

    /**
     * 获取答题记录信息
     */
    @Override
    @RequestMapping(value = "/answer/info" ,method = RequestMethod.POST)
    public ActionResult answerInfo(String key ,Integer answerId) {

        logger.info("[获取答题记录详情接口]:{}", "key="+ key + ",answerId=" + answerId);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if(user == null){
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        if (answerId == null || answerId == 0) {
            result.setSuccess(false);
            result.setMessage("参数不正确");
            return result;
        }

        try {
            Answer answer = answerService.findById(answerId);

            Question question = questionService.findQuestion(answer.getQuestionId());

            User qUser = userService.findById(question.getUserId());

            Boolean flag = answer.getAmount().compareTo(new BigDecimal(0)) == 0
                    && (question.getAmountStatus().equals(Question.AMOUNT_STATUS_TAKE) || question.getAmountStatus().equals(Question.AMOUNT_STATUS_RETURN));

            if(answer.getUserId().equals(user.getId())){
                result.setData(answer);
                result.put("flag",flag);
                result.put("questionTotalRight",question.getTotalRight());
                result.put("questionUserNickname",qUser.getNickname());
                result.put("questionUserAvatarUrl",qUser.getAvatarUrl());
                result.setSuccess(true);
                result.setMessage("获取答题记录详情成功");
            }else {
                result.setSuccess(false);
                result.setMessage("无权查看该记录");
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("获取答题记录详情失败");

            logger.warn("[获取答题记录接口异常]：", e);
        }

        return result;
    }


}
